#include "stdafx.h"
#include "ckCommand.h"
#include "ckConnection.h"

namespace ck
{
	Command::Command(Connection* pConnection, ADODB::_ConnectionPtr pConnectionPtr)
	{
		m_pConnection = pConnection;

		m_pConnectionPtr = pConnectionPtr;
		m_pCommandPtr = NULL;
		m_pRecordsetPtr = NULL;
	}


	Command::~Command()
	{
		if (m_pRecordsetPtr)
		{
			m_pRecordsetPtr->Close();
			//m_pRecordsetPtr->Release();
			m_pRecordsetPtr = NULL;
		}
		//if (m_pCommandPtr)
		//{
		//	m_pCommandPtr->Release();
		//}
	}

	ADODB::_RecordsetPtr Command::ExecuteQuery(const char* szSQL)
	{
		if (szSQL == NULL)
		{
			return NULL;
		}

		if (m_pRecordsetPtr)
		{
			m_pRecordsetPtr->Close();
			m_pRecordsetPtr->Release();
			m_pRecordsetPtr = NULL;
		}
		if (m_pCommandPtr != NULL)
		{
			m_pCommandPtr->Release();
			m_pCommandPtr = NULL;
		}
		
		HRESULT hr;
		hr = m_pCommandPtr.CreateInstance(__uuidof(ADODB::Command));
		if (FAILED(hr))
		{
			return NULL;
		}
		m_pCommandPtr->ActiveConnection = m_pConnectionPtr;
		m_pCommandPtr->CommandText = szSQL;

		try
		{
			ADODB::_RecordsetPtr pRecordsetPtr = m_pCommandPtr->Execute(NULL, NULL, ADODB::adCmdText);
			m_pRecordsetPtr = pRecordsetPtr;
		}
		catch (_com_error *e)
		{
			TRACE0(e->ErrorMessage());
		}
		

		return m_pRecordsetPtr;
	}
}

